package com.skyline.common.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.skyline.base.type.CommentType;

/**
 * 评论的标签
 * 
 * @author jairus chan
 */
public class CommentTag extends TagSupport {
	private static final long serialVersionUID = 1787065628804803098L;
	private static final Log LOGGER = LogFactory.getLog(CommentTag.class);
	private String objId;
	private String curClass;
	private String curStyle;
	private String normalClass;
	private String normalStyle;
	private String decStr;
	private String errorFunc;
	private String beforeSendFunc;
	private String completeFunc;
	private Integer maxSize;
	private String url;
	private String paramStr;
	private boolean hasParam;
	private Boolean arcCur;
	// private String pageKey;
	private static final String JUMP_TO_FUNCTION = "jumpTo";
	private static final String AJAX_BACK_FUNCTION = "ajaxPageBack";
	private String commentType;
	private Object resourceId;
	private Long ownerId;
	private String commentResourceURL;
	private String commentAgreeURL;
	private String commentDisagreeURL;
	private String commentDeleteURL;
	private String contextPath;
	private Integer pageSize = 18;
	private Integer divWidth = 640;
	private Long shareOwnerId;
	private Long shareResourceId;
	private String shareCommentType;
	private String resourceName;
	protected static final String URL_SUFFIX = ".html";

	private void initial() {
		url = contextPath + "/comment/getComment/" + commentType + "/" + resourceId + "/" + pageSize + URL_SUFFIX;
		commentResourceURL = contextPath + "/comment/commentResource/" + commentType + "/" + resourceId + URL_SUFFIX;
		commentAgreeURL = contextPath + "/comment/" + commentType + "/vote/AGREE/" + resourceId + URL_SUFFIX;
		commentDisagreeURL = contextPath + "/comment/" + commentType + "/vote/DISAGREE/" + resourceId + URL_SUFFIX;
		commentDeleteURL = contextPath + "/comment/" + commentType + "/delete" + URL_SUFFIX;
	}

	@Override
	public int doEndTag() throws JspException {
		initial();
		// System.out.println(generateTotleScript());
		try {

			pageContext.getOut().println(generateTotleScript());
		} catch (IOException e) {
			LOGGER.warn("生成comment出错", e);
		}
		return EVAL_BODY_INCLUDE;
	}

	private String generateTotleScript() {
		StringBuffer buffer = new StringBuffer();
		buffer.append(generateCommentInfoBar());
		buffer.append("<div id=\"" + objId + "PageDivTop\" style=\"width: " + divWidth + "px\" align=\"right\" ></div>");
		buffer.append("<table id=\""
				+ objId
				+ "Commentlist\"  width=\""
				+ divWidth
				+ "\" cellspacing=\"0\" cellpadding=\"0\" style=\"FONT-SIZE: 14px;LINE-HEIGHT: 16pt ;table-layout: fixed;WORD-BREAK: break-all; WORD-WRAP: break-word;\"></table>");
		buffer.append("<div id=\"" + objId + "PageDivBottom\" style=\"width: " + divWidth + "px\" align=\"right\" ></div>");
		buffer.append(generateMyComment());
		buffer.append("<script type=\"text/javascript\">var usingComment;");
		buffer.append("var ");
		buffer.append(objId);
		buffer.append("={\n");
		buffer.append(generatePageSetting());
		buffer.append(",\n");
		buffer.append(generateAjaxBack());
		buffer.append(",\n");
		buffer.append(generateFirstAskFunc());
		buffer.append(",\n");
		buffer.append(generateJumpTo());
		buffer.append("}\n");
		buffer.append(generateComment());
		buffer.append(generateReady());
		buffer.append("commentObjs[commentObjNum++]=" + objId + "Comment;");
		buffer.append("</script>");
		return buffer.toString();
	}

	private String generateCommentInfoBar() {
		String infobar = "<table width=\""
				+ divWidth
				+ "\" cellspacing=\"0\" cellpadding=\"0\" height=\"28\" style=\"table-layout: fixed;WORD-BREAK: break-all; WORD-WRAP: break-word;\">\n";
		infobar += "<tr bgcolor=\"#f2b600\">";
		infobar += "	<td><font id=\"" + objId + "Commentnum\" color=\"#ffffff\"></font></td>";
		infobar += "<td align=\"right\"><a id=\"" + objId + "a_hideOrShowComments\" class=\"a_hideOrShowComments\" href=\"#\" onclick=\""
				+ objId + "Comment.hideOrShowComments()\">-</a>&nbsp;</td>";
		infobar += "</tr></table>";
		return infobar;
	}

	private String generateReady() {
		return "jQuery(\"document\").ready(function(){" + objId + ".firstFunc();});";
	}

	private String generateComment() {

		String comment = "";
		comment += "var " + objId + "Comment=new Comment();\n";
		if (this.commentType.equals(CommentType.SHORTMESSAGE.toString())) {
			comment += objId + "Comment.resourceId=\"" + resourceId + "\";\n";
		} else {
			comment += objId + "Comment.resourceId=" + resourceId + ";\n";
		}
		comment += objId + "Comment.resourceName=\"" + resourceName + "\";\n";
		comment += objId + "Comment.type=\"" + commentType + "\";\n";
		// comment += objId + "Comment.loginedUserId=" + loginedUserId+";\n";
		comment += objId + "Comment.ownerId=" + ownerId + ";\n";

		comment += objId + "Comment.commentResourceURL=\"" + commentResourceURL + "\";\n";
		comment += objId + "Comment.agreeURL=\"" + commentAgreeURL + "\";\n";
		comment += objId + "Comment.disagreeURL=\"" + commentDisagreeURL + "\";\n";
		comment += objId + "Comment.deleteURL=\"" + commentDeleteURL + "\";\n";
		// comment += objId + "Comment.getLoginedUserURL=\"" + contextPath +
		// "/getlogineduser.html\";\n";
		comment += objId + "Comment.objId=\"" + objId + "\";\n";
		comment += objId + "Comment.commentAjax=" + objId + ";\n";
		comment += objId + "Comment.divWidth=" + divWidth + ";\n";
		return comment;
	}

	private String generateMyComment() {
		String myComment = "";
		myComment += "<div id=\"" + objId + "MyCommentDiv\"><font id=\"" + objId + "CommentFont\" color=\"red\"></font>" + "<div id=\""
				+ objId + "RefCommentInfo\" style=\"display: none\"><b>&nbsp; " + "<font id=\"" + objId
				+ "RefCommentInfoFont\" color=\"#004e90\"></font></b> " + "<font id=\"" + objId
				+ "RefCommentCommetidFont\" style=\"display: none\">0</font> " + "<a title=\"取消回复\" href=\"javascript:" + objId
				+ "Comment.cancelRefComment()\">" + "<img style=\"border: 0px\" alt=\"取消回复\" src=\"" + contextPath
				+ "/img/commons/fail_min.gif\"></a></div>" + "<div><table width='" + divWidth
				+ "' style=\"table-layout: fixed; WORD-BREAK: break-all; WORD-WRAP: break-word;\">"
				+ "<tr><td width='72' valign='top' align='center'>" + "<div id=\"" + objId + "LoginedUserDiv\" ></div></td>"
				+ "<td align=\"right\" valign='top'>" + "<textarea class='myComment' id=\"" + objId
				+ "MyComment\" cols=\"60\" rows=\"4\" onfocus=\"" + objId + "Comment.showTools()\"></textarea>" + "<div id=\"" + objId
				+ "Tools\" style=\"display: none\"><a href=\"javascript:" + objId + "Comment.insertSmiley()\">不能打开表情工具包</a></div>"
				+ "</td></tr></table></div>" + "<div align=\"right\" style=\"width: " + divWidth + "px\"><br>";
		if (commentType.equals("SHARE")) {
			myComment += "<input type=\"checkbox\" id=\"" + objId + "CommentToSource\" checked=true >同时评论到出处";
			myComment += "<input type=\"hidden\" id=\"" + objId + "ShareResourceId\" value=\"" + shareResourceId + "\">";
			myComment += "<input type=\"hidden\" id=\"" + objId + "ShareOwnerId\" value=\"" + shareOwnerId + "\">";
			myComment += "<input type=\"hidden\" id=\"" + objId + "ShareCommentType\" value=\"" + shareCommentType + "\">";
		}
		myComment += "<input class=\"btn_ok\" type=\"button\" onclick=\"" + objId + "Comment.commentResource()\" value=\"提交\">&nbsp;"
				+ "<input class=\"btn_cancel\" type=\"button\" onclick=\"" + objId
				+ "Comment.cancelComment()\" value=\"取消\">&nbsp;</div></div>";
		return myComment;
	}

	/**
	 * 产生Ajax请求
	 * 
	 * <pre>
	 * doAjax(url,paramStr+'curpage='+curpage,backFunc,errorFunc,beforeSendFunc);
	 * </pre>
	 */
	private String generateAjaxAsk(String curpage) {
		StringBuffer buffer = new StringBuffer("doAjax('");
		buffer.append(url);
		buffer.append("','");
		if (paramStr == null) {
			buffer.append("curpage='+");
			buffer.append(curpage);
		} else {
			if (hasParam) {
				buffer.append(paramStr);
				buffer.append("&curpage='+");
				buffer.append(curpage);
			} else {
				buffer.append("curpage='+");
				buffer.append(curpage);
			}
		}
		buffer.append(",");
		buffer.append(objId);
		buffer.append(".");
		buffer.append(AJAX_BACK_FUNCTION);
		if (errorFunc != null) {
			buffer.append(",");
			buffer.append(errorFunc);
		}
		if (beforeSendFunc != null) {
			buffer.append(",");
			buffer.append(beforeSendFunc);
		}
		if (completeFunc != null) {
			buffer.append(",");
			buffer.append(completeFunc);
		}
		buffer.append(");");
		return buffer.toString();
	}

	/**
	 * 产生Ajax回调
	 * 
	 * <pre>
	 * ajaxPageBack:function(data){
	 * var page=data.pageKey;
	 * jQuery('#pageDiv').html(pagination.generateTotalStr(page));
	 * successFunc(data);
	 * }
	 * </pre>
	 */
	private String generateAjaxBack() {
		StringBuffer buffer = new StringBuffer(AJAX_BACK_FUNCTION);
		buffer.append(":function(data){\n");
		buffer.append("var page=data.page");
		// buffer.append(pageKey);
		buffer.append(";\n");
		// String[] divIds = pageDivId.split(",");
		buffer.append(genDivUrlFunc());
		buffer.append(objId + "Comment.processData");
		buffer.append("(data);\n}\n");
		return buffer.toString();
	}

	private String genDivUrlFunc() {
		StringBuffer buffer = new StringBuffer();

		buffer.append("jQuery('#");
		buffer.append(objId + "PageDivTop");
		buffer.append("').html(");
		buffer.append(objId);
		buffer.append(".pagination.generateTotalStr(page));\n");

		buffer.append("jQuery('#");
		buffer.append(objId + "PageDivBottom");
		buffer.append("').html(");
		buffer.append(objId);
		buffer.append(".pagination.generateTotalStr(page));\n");

		return buffer.toString();
	}

	/**
	 * 产生第一次请求函数
	 * 
	 * <pre>
	 * firstFunc:function(){
	 * return doAjax(url,paramStr+'curpage='+1,backFunc,errorFunc);
	 * }
	 * </pre>
	 */
	private String generateFirstAskFunc() {
		String funcName = "firstFunc";
		StringBuffer buffer = new StringBuffer(funcName);
		buffer.append(":function(){\n $(\"#" + objId + "Commentlist\").html(\"<tr><td width='72'></td><td>正在载入评论...</td></tr>\");").append(
				"return ");
		buffer.append(generateAjaxAsk("1"));
		buffer.append("\n}\n");
		return buffer.toString();
	}

	/**
	 * 产生跳转函数
	 * 
	 * <pre>
	 * jumpTo:function (i){
	 * return doAjax(url,paramStr+'curpage='+i,backFunc,errorFunc);
	 * }
	 * </pre>
	 */
	private String generateJumpTo() {
		StringBuffer buffer = new StringBuffer(JUMP_TO_FUNCTION);
		buffer.append(":function").append(
				"(i){\n $(\"#" + objId + "Commentlist\").html(\"<tr><td width='72'></td><td>正在载入评论...</td></tr>\");");
		buffer.append(generateAjaxAsk("i"));
		buffer.append("\n}\n");
		return buffer.toString();
	}

	/**
	 * 产生分页设置
	 * 
	 * <pre>
	 * pagination:new Pagination({
	 * arcCur:arcCur,
	 * curClassStr:&quot;curClass&quot;,
	 * curStyleStr:&quot;curStyle&quot;,
	 * norClassStr:&quot;normalClass&quot;,
	 * norStyleStr:&quot;normalStyle&quot;,
	 * decStr:&quot;decStr&quot;,
	 * pageObj:&quot;objId&amp;quot,
	 * maxSize:maxSize
	 * })
	 * </pre>
	 */
	private String generatePageSetting() {
		StringBuffer buffer = new StringBuffer("pagination:new Pagination({arcCur:");
		boolean arc = arcCur == null ? false : arcCur;
		buffer.append(arc);
		buffer.append(",curClassStr:\"");
		buffer.append(StringUtils.trimToEmpty(curClass));
		buffer.append("\",curStyleStr:\"");
		buffer.append(StringUtils.trimToEmpty(curStyle));
		buffer.append("\",norClassStr:\"");
		buffer.append(StringUtils.trimToEmpty(normalClass));
		buffer.append("\",norStyleStr:\"");
		buffer.append(StringUtils.trimToEmpty(normalStyle));
		buffer.append("\",decStr:\"");
		buffer.append(StringUtils.trimToEmpty(decStr));
		buffer.append("\",pageObj:\"");
		buffer.append(objId);
		buffer.append("\",maxSize:");
		buffer.append(maxSize);
		buffer.append("})");
		return buffer.toString();
	}

	public void setObjId(String objId) {
		objId = StringUtils.trimToNull(objId);
		this.objId = (objId == null) ? "p" : objId;
	}

	public void setCurClass(String curClass) {
		this.curClass = curClass;
	}

	public void setCurStyle(String curStyle) {
		this.curStyle = curStyle;
	}

	public void setNormalClass(String normalClass) {
		this.normalClass = normalClass;
	}

	public void setNormalStyle(String normalStyle) {
		this.normalStyle = normalStyle;
	}

	public void setDecStr(String decStr) {
		this.decStr = decStr;
	}

	// public void setFirstFunc(String firstFunc) {
	// this.firstFunc = firstFunc;
	// }

	// public void setSuccessFunc(String successFunc) {
	// this.successFunc = successFunc;
	// }

	public void setErrorFunc(String errorFunc) {
		this.errorFunc = errorFunc;
	}

	public void setBeforeSendFunc(String beforeSendFunc) {
		this.beforeSendFunc = beforeSendFunc;
	}

	public void setCompleteFunc(String completeFunc) {
		this.completeFunc = completeFunc;
	}

	public void setMaxSize(Integer maxSize) {
		this.maxSize = maxSize;
	}

	public void setParamStr(String paramStr) {
		this.paramStr = StringUtils.trimToNull(paramStr);
		if (null == this.paramStr) {
			hasParam = false;
		} else {
			hasParam = true;
		}
	}

	public void setArcCur(Boolean arcCur) {
		this.arcCur = arcCur;
	}

	// public void setPageKey(String pageKey) {
	// this.pageKey = pageKey;
	// }

	// public void setPageDivId(String pageDivId) {
	// this.pageDivId = pageDivId;
	// }

	public void setResourceId(Object resourceId) {
		this.resourceId = resourceId;
	}

	// public void setLoginedUserId(Long loginedUserId) {
	// this.loginedUserId = loginedUserId;
	// }

	public void setCommentType(String commentType) {
		this.commentType = commentType;
	}

	public void setContextPath(String contextPath) {
		this.contextPath = contextPath;
	}

	public void setOwnerId(Long ownerId) {
		this.ownerId = ownerId;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

	public void setDivWidth(Integer divWidth) {
		this.divWidth = divWidth;
	}

	public void setShareOwnerId(Long shareOwnerId) {
		this.shareOwnerId = shareOwnerId;
	}

	public void setShareResourceId(Long shareResourceId) {
		this.shareResourceId = shareResourceId;
	}

	public void setShareCommentType(String shareCommentType) {
		this.shareCommentType = shareCommentType;
	}

	public void setResourceName(String resourceName) {
		this.resourceName = resourceName.replaceAll("\"", " ");
		// this.resourceName
	}

	// public static void main(String[] args){
	// String str="\"";
	// System.out.println(str);
	// System.out.println(str.replaceAll("\"", " "));
	// }

	/*
	 * public static void main(String... strings) { CommentTag tag = new
	 * CommentTag(); tag.setObjId("objId"); // tag.setCurClass("curClass"); //
	 * tag.setCurStyle("curStyle"); // tag.setNormalClass("normalClass"); //
	 * tag.setNormalStyle("normalStyle"); // tag.setDecStr(" decStr");
	 * //tag.setFirstFunc("firstFunc"); //tag.setSuccessFunc("successFunc");
	 * tag.setErrorFunc("errorFunc"); tag.setMaxSize(5); //tag.setUrl("url"); //
	 * tag.setParamStr("paramStr"); // tag.setArcCur(false);
	 * tag.setPageKey("pageKey"); //tag.setPageDivId("pageDivId");
	 * System.out.println(tag.generateTotleScript()); }
	 */

}
